package com.zx.JDK特性.jdk1_8;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import lombok.Data;
import lombok.experimental.Accessors;

public class Stream4_FlatMap {

    // flatMap 的作用是将集合中的集合中提取数据，进行数据提取/转换
    public static void main(String[] args) {

        List<Group> groups = Arrays.asList(
                new Group().setId(1).setGroupName("普通用户")
                        .addUser(new UserDto().setId(1L).setName("AA").setSex(0))
                        .addUser(new UserDto().setId(2L).setName("BB").setSex(1))
                        .addUser(new UserDto().setId(3L).setName("CC").setSex(0))
                ,
                new Group().setId(2).setGroupName("会员")
                        .addUser(new UserDto().setId(4L).setName("DD").setSex(1))
                        .addUser(new UserDto().setId(5L).setName("EE").setSex(1))
                        .addUser(new UserDto().setId(6L).setName("FF").setSex(0)),
                new Group().setId(3).setGroupName("超级会员")
                        .addUser(new UserDto().setId(7L).setName("GG").setSex(0))
                        .addUser(new UserDto().setId(8L).setName("HH").setSex(0))
                        .addUser(new UserDto().setId(9L).setName("II").setSex(0))
        );
        // 提取性别
        groups.stream().flatMap(list -> list.getUserList().stream().map(user -> user.getSex()))
                .collect(Collectors.toList()).forEach(System.out::println);

        System.out.println("###############################");
        // 提取姓名
        groups.stream().flatMap(list -> list.getUserList().stream().map(user -> user.getName()))
                .collect(Collectors.toList()).forEach(System.out::println);
        // 提取用户
        System.out.println("###############################");
        groups.stream().flatMap(group -> group.getUserList().stream()).collect(Collectors.toList())
                .forEach(System.out::println);

    }

    @Data
    @Accessors(chain = true)
    private static class Group {

        private String groupName;

        private Integer id;

        private List<UserDto> userList = new ArrayList<>();

        public Group addUser(UserDto user) {
            this.userList.add(user);
            return this;
        }

    }

    @Data
    @Accessors(chain = true)
    private static class UserDto {

        private Long id;

        private String name;

        private Integer sex;

    }

}

